/**
 * Created by gaoyj on 2018/6/27.
 */
window.onload = function (ev) {
    topbar.hide();
};
var myDate = new Date();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
if (month < 10) {
    month = "0" + month;
}
if (day < 10) {
    day = "0" + day;
}
var _start = myDate.getFullYear() + '-' + month + '-' + day + " 00:00:00";
var _end = myDate.getFullYear() + '-' + month + '-' + day + " 23:59:59";
$("#startTime").val(_start);
$("#endTime").val(_end);
$("#validity").val(_end);
laydate.render({
    elem: '#startTime',
    type: 'datetime',
});
laydate.render({
    elem: '#endTime' //指定元素
    , type: 'datetime',
});
laydate.render({
    elem: '#validity' //指定元素
    , type: 'datetime',
});
//初始化角色选项
initRoleOption();
$('#dataTable').bootstrapTable({
    url: '/AdminInterface/queryTitleList',
    height: $(window).height() - 200,
    pageSize: 30,
    pagination: true,
    pageList: [30, 50, 100],
    clickToSelect: true,
    singleSelect: true,
    queryParams: queryParams,
    uniqueId: 'id',
    queryParamsType: '',
    sidePagination: 'server',
    responseHandler: function (res) {
        return {
            "total": res.total,//总页数
            "rows": res.resultList   //数据
        };
    },
    columns: [
        {
            checkbox: true
        }, {
            width: '3px',
            align: 'center',
            formatter: function (v, row, index) {
                return index + 1
            }
        },
        {
            width: '40px',
            align: 'center',
            field: 'title',
            title: '标题',
            formatter: function (v, o) {
                return '<a href="javascript:void(0)" name="createLink" onclick="editSupFunc(' + o.id + ')">' + o.title + '</a>'
            }
        }, {
            width: '20px',
            align: 'center',
            field: 'adminName',
            title: '发布人'
        },
        {
            width: '20px',
            align: 'center',
            field: 'bindRoleNames',
            title: '已绑定角色',
            formatter: function (v, row, index) {
                return v == null ? "" : v;
            }
        },
        {
            width: '20px',
            align: 'center',
            field: 'bindRoleIds',
            title: '已绑定角色',
            visible: false
        },
        {
            width: '20px',
            align: 'center',
            field: 'type',
            title: '交接性质',
            formatter: function (v, row, index) {
                switch (v) {
                    case 1:
                        return "正常";
                        break;
                    case 2:
                        return "一般";
                        break;
                    case 3:
                        return "重点注意";
                        break;
                    case 4:
                        return "<span style='color: red'>全体注意</span>";
                        break;
                    case 5:
                        return "新增渠道";
                        break;
                }
            }
        }, {
            width: '20px',
            align: 'center',
            field: 'sendTime',
            title: '发布时间'
        }, {
            width: '20px',
            align: 'center',
            field: 'validity',
            title: '有效期至'
        }
    ]
});

$("#search").click(function () {
    var timeAdd = new Date($("#startTime").val());
    var timeEnd = new Date($("#endTime").val());
    if (timeAdd > timeEnd) {
        layer.msg("开始时间不能大于结束时间");
        return false;
    }
    $("#dataTable").bootstrapTable("refresh");
});

function queryParams(params) {
    return {
        size: params.pageSize,
        page: params.pageNumber,
        startTime: $("#startTime").val(),
        endTime: $("#endTime").val(),
    };
}

//弹出
function editSupFunc(objid) {
    window.open("/workLogInfo?id=" + objid);
}

function addFun(v) {
    $("#addModalLabel").attr("msg", v);
    if (v == 1) {
        $("#addModalLabel").html("新建交接内容");
        $("#addForm input,#addForm select,#addForm textarea").val("");
        KindEditor.instances[0].html("");
        initRoleOption();
    } else {
        $("#addModalLabel").html("修改交接内容");
        var rows = $('#dataTable').bootstrapTable("getSelections");
        if (rows == null || rows.length === 0) {
            layer.msg("请选择要操作的数据");
            return;
        }
        //角色赋值
        queryBoundRole(rows[0].bindRoleIds);
        $("#titleAdd").val(rows[0].title);
        $("#validity").val(rows[0].validity);
        $("#type").val(rows[0].type);
        $("#contentAdd").val(rows[0].content);
        editor.html(rows[0].content);
    }
    $("#addModal").modal("show")
}

//查询已绑定角色
function queryBoundRole(bindRoleIds) {
    $.ajax({
        type: "POST",
        url: "/adminButton/queryBoundRole",
        dataType: "json",
        data: {bindRoleIds: bindRoleIds},
        success: function (data) {
            var roleIds = [];
            if (data != null && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    roleIds.push(data[i].id);
                }
            }
            $('.selectpicker').selectpicker('val', roleIds);
            $('.selectpicker').selectpicker('refresh');
        },
        beforeSend: function () {
        }
    });
}

//初始化角色
function initRoleOption() {
    $.ajax({
        type: "POST",
        url: "/adminButton/getAllRole",
        dataType: "json",
        success: function (data) {
            $("#bindRoleIds").html("");
            var str = "";
            if (data != null && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += '<option value=' + data[i].id + '>' + data[i].name + '</option>'
                }
            }
            $("#bindRoleIds").append(str);
            //缺一不可  
            $('.selectpicker').selectpicker('refresh');
            $('.selectpicker').selectpicker('render');
        },
        beforeSend: function () {
        }
    });
}

$("#addBtn").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    // editor.sync();
    var msg = $("#addModalLabel").attr("msg");
    var url;
    var data;
    var bindRoleIdsArr = $("#bindRoleIds").val();
    if (bindRoleIdsArr == null || bindRoleIdsArr == '' || bindRoleIdsArr == undefined) {
        layer.msg("请选择角色");
        return;
    }
    var timeAdd = new Date($("#validity").val());
    var nowDate = new Date();
    if (timeAdd < nowDate) {
        layer.msg("有效期不能小于当前时间");
        return false;
    }

    var bindRoleIds = bindRoleIdsArr.join(',');
    if (msg == 1) {
        url = "/AdminInterface/contentIn";
        data = {
            title: $.trim($("#titleAdd").val()),
            validity: $("#validity").val(),
            type: $.trim($("#type").val()),
            bindRoleIds: bindRoleIds,
            content: $.trim($("#contentAdd").val()),
        }
    } else {
        url = "/AdminInterface/updateContent";
        data = {
            id: rows[0].id,
            title: $.trim($("#titleAdd").val()),
            validity: $.trim($("#validity").val()),
            type: $.trim($("#type").val()),
            bindRoleIds: bindRoleIds,
            content: $.trim($("#contentAdd").val())
        }
    }
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                layer.msg(data.message);
                $("#addModal").modal("hide");
            } else {
                layer.msg(data.message)
            }
        },
        beforeSend: function () {
        }
    });
})
var editor;
var options = {
    cssPath: 'js/kindeditor-4.1.10/plugins/code/prettify.css',
    filterMode: true,
    resizeType: 1,
    allowPreviewEmoticons: false,
    allowImageUpload: true,
    allowFileManager: true,
    uploadJson: '/news/getPicUrl',
    fileManagerJson: '/js/kindeditor-4.1.10/jsp/file_manager_json.jsp',
    afterUpload: function () {
        this.sync();
    },
    afterBlur: function () {
        this.sync();
    },
    width: '100%',
    height: '300px',
    items: [
        'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline']
};
KindEditor
    .ready(function (K) {
        editor = K.create('#contentAdd', options);
    });